#include "dk_client.h"
#include "configdialog.h"
#include "ui_dk_client.h"
#include <QFile>
#include <QDir>

QString $skyrim_conf_path=QDir::homePath()+"\\AppData\\Local\\Skyrim\\";
QString $skyrim_path;
QString $skyrim_masterfile="Skyrim.esm";

QFileInfoList FileList;
List *list;
bool Switch_0=0;

ConfigDialog *configure;

int row;

Dk_Client::Dk_Client(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Dk_Client)
{

    ui->setupUi(this);
    ReadConfig();

    connect(ui->tableWidget,SIGNAL(currentCellChanged(int,int,int,int)),this,SLOT(RowSelected(int,int,int,int)));
    connect(ui->tableWidget,SIGNAL(cellChanged(int,int)),this,SLOT(IsChange(int,int)));
    connect(ui->toolButton_up,SIGNAL(clicked()),this,SLOT(MoveUp()));
    connect(ui->toolButton_down,SIGNAL(clicked()),this,SLOT(MoveDown()));
    connect(ui->toolButton_del,SIGNAL(clicked()),this,SLOT(Delete()));
    connect(ui->pushButton_reset,SIGNAL(clicked()),this,SLOT(Reset()));
    connect(ui->pushButton_apply,SIGNAL(clicked()),this,SLOT(Apply()));
    connect(ui->toolButton_config,SIGNAL(clicked()),this,SLOT(Config()));
    connect(ui->checkBox_All,SIGNAL(stateChanged(int)),this,SLOT(SelectAll(int)));
}

Dk_Client::~Dk_Client()
{
    delete ui;
}


bool Dk_Client::Reset()
{
    Switch_0=1;
    row=0;
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    QTableWidgetItem **checkbox;
    bool *fileExist;
    QSortlist *sortlist;
    int i,size,tmpnum;
    QString tmp;
    QStringList fliter;

    QDir dir($skyrim_path+"\\Data\\");
    fliter<<"*.esm"<<"*.esp";
    dir.setFilter(QDir::Files);
    FileList=dir.entryInfoList(fliter);

    row=FileList.size();
    list=new List;
    list->ch=new QString[row];
    checkbox=new QTableWidgetItem *[row];
    sortlist=new QSortlist[row];
    fileExist=new bool[row];
    memset(fileExist,0,row);

    QFile file0($skyrim_conf_path+"loadorder.txt");
    QFile file1($skyrim_conf_path+"plugins.txt");

    file1.open(QIODevice::ReadWrite|QIODevice::Text);
    for(i=0;i<row;)
    {
        do{tmp=file1.readLine();}while(tmp.left(1).toLatin1()=="#");
        if((size=tmp.length()-1)<5) break;
        tmp=tmp.left(size);
        if((IsNotExist(tmp))==-1) continue;
        list->ch[i]=tmp;
        i++;
    }
    list->num=i;
    file1.close();

    file0.open(QIODevice::ReadOnly|QIODevice::Text);
    for(i=0,tmpnum=0;i<row;)
    {
        do{tmp=file0.readLine();}while(tmp.left(1).toLatin1()=="#");
        if((size=tmp.length()-1)<5) break;
        tmp=tmp.left(size);
        if((tmpnum=IsNotExist(tmp))==-1) continue;
        sortlist[i].id=tmpnum;
        fileExist[tmpnum]=1;
        sortlist[i].ischecked=IsActive(tmp);
        i++;
    }

    if(QString::compare(FileList.at(sortlist[0].id).fileName(),$skyrim_masterfile,Qt::CaseInsensitive)!=0)
    {
        int l=IsNotExist($skyrim_masterfile);
        if(l!=-1)
        {
            tmpnum=1;
            while(sortlist[tmpnum].id-l)    tmpnum++;
            sortlist[tmpnum].id=sortlist[0].id;
            sortlist[tmpnum].ischecked=sortlist[0].ischecked;
            sortlist[0].id=l;
        }
    }

    file0.close();
    sortlist[0].ischecked=1;

    for(int j=0;i<row;j++)
    {
        if(fileExist[j]) continue;
        else
        {
            sortlist[i].id=j;
            sortlist[i].ischecked=0;
            i++;
        }
    }

    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
    ui->tableWidget->verticalHeader()->setVisible(0);
    ui->tableWidget->setRowCount(row);
    ui->tableWidget->setColumnCount(7);
    ui->tableWidget->setColumnWidth(0,20);
    ui->tableWidget->setColumnWidth(1,260);
    ui->tableWidget->setColumnWidth(2,50);
    ui->tableWidget->setColumnWidth(3,50);
    ui->tableWidget->setColumnWidth(4,100);
    ui->tableWidget->setColumnWidth(5,150);
    ui->tableWidget->setColumnWidth(6,150);
    ui->tableWidget->resizeRowsToContents();
    ui->tableWidget->setHorizontalHeaderLabels(QStringList() <<tr("")<<tr("Plugins")<<tr("Order")<<tr("Index")<<tr("Size")<<tr("Modified Time")<<tr("Created Time"));
    ui->tableWidget->setStyleSheet("background-color:rgba(200,255,255,255)");
    ui->tableWidget->setStyleSheet("selection-background-color: blue");
    for(int i=0;i<row;i++)
    {
        checkbox[i]=new QTableWidgetItem();        
        sortlist[i].ischecked?checkbox[i]->setCheckState(Qt::Checked):checkbox[i]->setCheckState(Qt::Unchecked);
        ui->tableWidget->setItem(i,0,checkbox[i]);
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(FileList.at(sortlist[i].id).fileName()));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(QString::number((i+1),10)));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(QString::number(FileList.at(sortlist[i].id).size())+" Byte"));
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(FileList.at(sortlist[i].id).lastModified().toString("yyyy-MM-dd hh:mm:ss")));
        ui->tableWidget->setItem(i,6,new QTableWidgetItem(FileList.at(sortlist[i].id).created().toString("yyyy-MM-dd hh:mm:ss")));
        ui->tableWidget->item(i,4)->setTextAlignment(Qt::AlignRight);
        ui->tableWidget->item(i,5)->setTextAlignment(Qt::AlignRight);
        ui->tableWidget->item(i,6)->setTextAlignment(Qt::AlignRight);
    }
    MakeOrder();
    QTableWidgetItem *mustcheck = new QTableWidgetItem;    
    mustcheck->setIcon(QIcon((":/images/mustcheck.png")));
    ui->tableWidget->setItem(0,0,mustcheck);
    Switch_0=0;

    delete []sortlist;
    delete []checkbox;
    delete []list->ch;
    delete []list;
    delete []fileExist;

    return 1;
}



int Dk_Client::IsNotExist(QString name)
{
    for (int i=0;i<row;i++) if(QString::compare(name,FileList.at(i).fileName(),Qt::CaseInsensitive)==0) return i;
    return -1;
}

bool Dk_Client::IsActive(QString name)
{
    for (int i=0;i<list->num;i++) if(QString::compare(name,list->ch[i])==0) return 1;
    return 0;
}

bool Dk_Client::RowSelected(int CurRow, int CurColumn,int PreRow, int PreColumn)
{
    if(Switch_0)  return 0;
    if((CurRow==PreRow))  return 0;
    else if ((CurRow<0)||(CurRow>=row))  return 0;
    else if ((CurRow>1)&&(CurRow<row-1)) setEnableButton(1,1,1);
    else if (CurRow==1)                  setEnableButton(0,1,1);
    else if (CurRow==0)                  setEnableButton(0,0,0);
    else if (CurRow==row-1)              setEnableButton(1,0,1);
    return 1;
    CurColumn^=PreColumn;
}

bool Dk_Client::setEnableButton(bool up, bool down, bool del)
{
    ui->toolButton_up->setEnabled(up);
    ui->toolButton_down->setEnabled(down);
    ui->toolButton_del->setEnabled(del);
    return 1;
}

bool Dk_Client::MoveUp(){return MoveUpDown(-1);}
bool Dk_Client::MoveDown(){return MoveUpDown(1);}

bool Dk_Client::MoveUpDown(int i)
{
    if(Switch_0)  return 0;
    if(i!=-1&&i!=1) return 0;
    register int CurRow=ui->tableWidget->currentRow();
    if(CurRow<0||CurRow>=row)  return 0;
    QTableWidgetItem *tmpcheck=new QTableWidgetItem;
    tmpcheck->setCheckState(ui->tableWidget->item(CurRow,0)->checkState());
    ui->tableWidget->item(CurRow,0)->setCheckState(ui->tableWidget->item(CurRow+i,0)->checkState());
    ui->tableWidget->item(CurRow+i,0)->setCheckState(tmpcheck->checkState());
    QString *b=new QString[2];
    *b=ui->tableWidget->item(CurRow+i,1)->text();
    *(b+1)=ui->tableWidget->item(CurRow,1)->text();
    ui->tableWidget->setItem(CurRow,1,new QTableWidgetItem(*b));
    ui->tableWidget->setItem(CurRow+i,1,new QTableWidgetItem(*(b+1)));
    for(int j=4;j<7;j++)
    {
        *b=ui->tableWidget->item(CurRow+i,j)->text();
        *(b+1)=ui->tableWidget->item(CurRow,j)->text();
        ui->tableWidget->setItem(CurRow,j,new QTableWidgetItem(*b));
        ui->tableWidget->item(CurRow,j)->setTextAlignment(Qt::AlignRight);
        ui->tableWidget->setItem(CurRow+i,j,new QTableWidgetItem(*(b+1)));
        ui->tableWidget->item(CurRow+i,j)->setTextAlignment(Qt::AlignRight);
    }
    ui->tableWidget->setCurrentCell(CurRow+i,QAbstractItemView::SelectRows);
    delete []tmpcheck;
    delete []b;
    return 1;
}


bool Dk_Client::Delete()
{
    if(Switch_0)  return 0;
    int CurRow=ui->tableWidget->currentRow();
    if(CurRow<1||CurRow>=row)   return 0;
    row--;
    for(int i=CurRow+1;i<=row;i++) ui->tableWidget->setItem(i,3,new QTableWidgetItem(QString::number(i,10)));
    ui->tableWidget->removeRow(CurRow);
    MakeOrder();
    return 1;
}

bool Dk_Client::IsChange(int x, int y)
{
    if(Switch_0)  return 0;
    if(y!=0||x<1||x>=row)    return 0;
    MakeOrder();
    return 0;
}

bool Dk_Client::Apply()
{
    if(Switch_0)  return 0;
    QFile file0($skyrim_conf_path+"loadorder.txt");
    QFile file1($skyrim_conf_path+"plugins.txt");
    file0.open(QIODevice::WriteOnly|QIODevice::Text);
    QTextStream out0(&file0);
    out0<<ui->tableWidget->item(0,1)->text()<<endl;
    for(int i=1;i<row;i++)  out0<<ui->tableWidget->item(i,1)->text()<<endl;
    file0.close();
    file1.open(QIODevice::WriteOnly|QIODevice::Text);
    QTextStream out1(&file1);
    for(int i=1;i<row;i++)
    {
        if(ui->tableWidget->item(i,0)->checkState()==Qt::Checked)
            out1<<ui->tableWidget->item(i,1)->text()<<endl;
    }
    file1.close();
    return 1;
}

bool Dk_Client::SelectAll(int state)
{
    if(Switch_0)  return 0;
    if(row<2)   return 0;
    if(state)
    {
        for (int i=1;i<row;i++)
        {
            ui->tableWidget->item(i,0)->setCheckState(Qt::Checked);
        }
        return 1;
    }
    else
    {
        for (int i=1;i<row;i++)
        {
            ui->tableWidget->item(i,0)->setCheckState(Qt::Unchecked);
        }
        return 1;
    }
}

bool Dk_Client::MakeOrder()
{
    int i,j;
    ui->tableWidget->setItem(0,2,new QTableWidgetItem("00"));
    for(i=1,j=1;(i<row);i++)
    {
        if(ui->tableWidget->item(i,0)->checkState()==Qt::Checked)
        {
            if(j<16)    ui->tableWidget->setItem(i,2,new QTableWidgetItem("0"+QString::number(j,16).toUpper()));
            else        ui->tableWidget->setItem(i,2,new QTableWidgetItem(QString::number(j,16).toUpper()));
            j++;
        }
        else    ui->tableWidget->setItem(i,2,new QTableWidgetItem(""));
    }
    return 1;
}


bool Dk_Client::Config()
{
    if(Switch_0)  return 0;
    configure=new ConfigDialog(this);
    configure->show();
    if(!configure->exec())  return 0;
    $skyrim_path=configure->linePath->text();
    WriteConfig();
    Reset();
    return 1;
}

bool Dk_Client::ReadConfig()
{
    QSettings *file=new QSettings("config.ini",QSettings::IniFormat,0);
    $skyrim_path=file->value("/skyrim/path","0").toString();
    if($skyrim_path.length()<2) Config();
    else    Reset();
    delete file;
    return 1;
}

bool Dk_Client::WriteConfig()
{
    QSettings *file=new QSettings("config.ini",QSettings::IniFormat,0);
    file->setValue("/skyrim/path",$skyrim_path);
    delete file;
    return 1;
}

